package com.alisls.shequtao.service.goods.service.impl;

import com.alisls.shequtao.service.goods.dto.GoodsDTO;
import com.alisls.shequtao.service.goods.dto.SkuDetailDTO;
import com.alisls.shequtao.service.goods.dto.SpuDTO;
import com.alisls.shequtao.service.goods.dto.SpuDetailDTO;
import com.alisls.shequtao.service.goods.service.GoodsService;
import com.alisls.shequtao.service.goods.service.SkuService;
import com.alisls.shequtao.service.goods.service.SpuService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 商品服务
 *
 * @author Ke Wang
 */
@Service("goodsService")
@AllArgsConstructor
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    private final SpuService spuService;

    private final SkuService skuService;

    @Override
    public GoodsDTO saveSpuWithSkus(GoodsDTO goodsDTO) {
        // 保存spu
        SpuDetailDTO spuDetailDTO = generateSpuDTO(goodsDTO);
        spuService.saveSpuAndSpuDetail(spuDetailDTO);

        // 保存skus
        List<SkuDetailDTO> skuDetailDTOs = generateSkuDTOs(goodsDTO, spuDetailDTO);
        skuService.saveSkuAndSkuDetail(skuDetailDTOs);
        return goodsDTO;
    }

    private SpuDetailDTO generateSpuDTO(GoodsDTO goodsDTO) {
        SpuDetailDTO spuDetailDTO = new SpuDetailDTO();
        BeanUtils.copyProperties(goodsDTO, spuDetailDTO);
        return spuDetailDTO;
    }

    private List<SkuDetailDTO> generateSkuDTOs(GoodsDTO goodsDTO, SpuDTO spuDTO) {
        List<SkuDetailDTO> skuDetailDTOs = goodsDTO.getSkuDetailDTOs();
        if (CollectionUtils.isEmpty(skuDetailDTOs)) {
            return null;
        }

        skuDetailDTOs.forEach(skuDetailDTO -> skuDetailDTO.setSpuDTO(spuDTO));
        return skuDetailDTOs;
    }

}
